//
//  HMComposePictureView.swift
//  WeiBo14
//
//  Created by HM on 16/3/11.
//  Copyright © 2016年 HM. All rights reserved.
//  发微博界面的配图视图的控件

import UIKit

class HMComposePictureView: UICollectionView {
    
    // 当加号按钮点击的时候会执行这个闭包
    var selectedPictureClosure: (()->())?
    
    lazy var images: [UIImage] = [UIImage]()

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: layout)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        backgroundColor = UIColor.clearColor()
        hidden = true
        // 注册cell
        self.registerClass(HMComposePictureCell.self, forCellWithReuseIdentifier: HMComposePictureViewCellId)
        // 设置数据源
        dataSource = self
        delegate = self
        // 设置条目大小
    }
    
    // 提供给外界添加图片的方法
    func addImage(image: UIImage) {
        images.append(image)
        hidden = false
        // 刷新数据
        self.reloadData()
    }
    
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let itemMargin: CGFloat = 5
        let itemWH = CGFloat(Int((self.frame.width - 2 * itemMargin) / 3))
        
        // 能够获取到当前控件的最新宽高
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: itemWH, height: itemWH)
        // 设置条目之前的间距
        layout.minimumInteritemSpacing = itemMargin
        layout.minimumLineSpacing = itemMargin
    }
}


private let HMComposePictureViewCellId = "HMComposePictureViewCellId"

// MARK: - UICollectionViewDataSource
extension HMComposePictureView: UICollectionViewDataSource, UICollectionViewDelegate {
    
    // 返回有多少张图片
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let count = images.count
        // 如果count == 0 或者 count == 9 就返回 count
        // 否则返回count + 1 (因为需要添加一个加号按钮)
        return (count == 0 || count == 9) ? count : count + 1
    }
    
    
    // 每一张图片对应的cell
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(HMComposePictureViewCellId, forIndexPath: indexPath) as! HMComposePictureCell
        // 给cell设置图片
        if indexPath.item == images.count {
            // 代表最后一个加号按钮
            cell.image = nil
        }else{
            cell.image = images[indexPath.item]
        }
        
        cell.deleteButtonClickClosure = {[weak self] (cell: HMComposePictureCell) in
            // 1. 取到当前cell所在的item(indexPath)
            if let indexPath = self?.indexPathForCell(cell) {
                // 2. 移除数据
                self?.images.removeAtIndex(indexPath.item)
                // 3. 刷新collectionView
                self?.reloadData()
            }
        }
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        print("cell点击了")
        collectionView.deselectItemAtIndexPath(indexPath, animated: true)
        // 判断是否是加号按钮点击
        if indexPath.item == images.count {
            // 执行闭包
            selectedPictureClosure?()
        }
    }
}


// 自定义cell

private class HMComposePictureCell: UICollectionViewCell {
    
    // 删除按钮点击执行的闭包
    var deleteButtonClickClosure:((cell: HMComposePictureCell)->())?
    
    var image: UIImage? {
        didSet{
            deleteButton.hidden = image == nil
            if image != nil {
                imageView.image = image
                imageView.highlightedImage = image
            }else{
                // 设置成加号按钮
                imageView.image = UIImage(named: "compose_pic_add")
                imageView.highlightedImage = UIImage(named: "compose_pic_add_highlighted")
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        // 1. 添加一个imageView
        contentView.addSubview(imageView)
        contentView.addSubview(deleteButton)
        
        
        // 2. 添加约束
        imageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView)
        }
        
        deleteButton.snp_makeConstraints { (make) -> Void in
            make.top.trailing.equalTo(contentView)
        }
    }
    
    @objc private func delebuttonClick(){
        print("删除按钮点击")
        deleteButtonClickClosure?(cell: self)
    }
    
    // MARK: - 懒加载控件
    private lazy var imageView: UIImageView = {
        let imageView = UIImageView()
        imageView.contentMode = .ScaleAspectFill
        imageView.clipsToBounds = true
        return imageView
    }()
    
    // 删除按钮
    private lazy var deleteButton: UIButton = {
        let button = UIButton()
        button.addTarget(self, action: "delebuttonClick", forControlEvents: UIControlEvents.TouchUpInside)
        button.setImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
        return button
    }()
    
}